package com.efounder.fragment;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.efounder.activity.AboutActivityNew;
import com.efounder.activity.BlankActivity;
import com.efounder.activity.LxSettingActivity;
import com.efounder.activity.SettingActivity;
import com.efounder.activity.TestActivity;
import com.efounder.chat.activity.CreateUserQRCode;
import com.efounder.chat.activity.MultiLanguageActivity;
import com.efounder.chat.activity.ThemePreferenceActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.LogoutEvent;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.RingVibratorUtils;
import com.efounder.chat.zxing.qrcode.MipcaActivityCapture;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.bean.MyThemeBean;
import com.efounder.frame.manager.ThemeManager;
import com.efounder.frame.utils.Constants;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.model.APKUpdateManager;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AppContext;
import com.efounder.util.CommonSettingManager;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.FileDeleteUtil;
import com.efounder.util.FileSizeUtil;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.LogOutUtil;
import com.efounder.util.LoginManager;
import com.efounder.util.StorageUtil;
import com.efounder.util.ToastUtil;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.appcontext.AppConstant;
import com.pansoft.start.LoginCheckManager;
import com.utilcode.util.ReflectUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;

import skin.support.SkinCompatManager;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

//import com.efounder.deviceadmin.DisableEvent;


@SuppressLint("SdCardPath")
public class
LeftDrawerFragment extends BaseFragment implements View.OnClickListener {
    private static final String TAG = "LeftDrawerFragment";


    private String avatar = "";
    private ImageView iv_avatar;

    private TextView tv_name;
    private TextView tv_fxid;
    private ImageView user_sex;
    private String fxid;
    private String nick;
    private String sex;
    private User user;
    private View rootView;


    private StorageUtil storageUtil;

    private SwitchCompat ringSwitch;
    private SwitchCompat vibratorSwitch;
    private SwitchCompat noBrotherSwitch;


    /**
     * 高级设置
     */
    private LinearLayout advancedSetting;
    /**
     * 扫一扫
     */
    private LinearLayout saoyisao;
    /**
     * 清除缓存
     */
    private LinearLayout cleanSession;

    /**
     * 修改密码
     */
    private LinearLayout llChangepwd;
    /**
     * 多语言
     */
    private LinearLayout ll_multi_language;
    /**
     * 切换主题
     */
    private LinearLayout llChangeSkin;
    /**
     * 设置
     */
    private LinearLayout llSetting;


    /**
     * 缓存大小
     */
    private TextView cacheSize;

    /**
     * 换肤
     */
    private MyThemeBean changeTheme;
    private LinearLayout llSwitchChangeSkin;
    private SwitchCompat switchChangeSkin;
    private TextView tvSwitchSkin;

    /**
     * 两个缓存文件大小download  meeting文件夹
     */
    private double cacheFileSize1, cacheFileSize2;

    APKUpdateManager updateManager;
    private ImageView user_role;
    private LXGlideImageLoader lxGlideImageLoader;

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        lxGlideImageLoader = LXGlideImageLoader.getInstance();

        initView(inflater, container);
        //铃声，振动设置，免打扰设置
        initRingVibrator();

        return rootView;
    }

    private void initView(LayoutInflater inflater, ViewGroup container) {
        rootView = inflater.inflate(R.layout.fragment_left_drawer, container, false);
        LinearLayout re_myinfo = (LinearLayout) rootView.findViewById(
                R.id.re_myinfo);
        re_myinfo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                ChatActivitySkipUtil.startMyUserInfoActivity(getActivity());
            }

        });
        //二维码
        ImageView user_qr_code = (ImageView) rootView.findViewById(R.id.user_qr_code);
        user_qr_code.setOnClickListener(this);
        updateManager = new APKUpdateManager();
        // avatar = user.getAvatar();
        iv_avatar = (ImageView) re_myinfo.findViewById(R.id.iv_avatar);
        tv_name = (TextView) re_myinfo.findViewById(R.id.tv_name);
        tv_fxid = (TextView) rootView.findViewById(R.id.tv_fxid);
        user_sex = (ImageView) re_myinfo.findViewById(R.id.iv_sex);
        user_role = (ImageView) re_myinfo.findViewById(R.id.iv_role);
        user_sex.setVisibility(View.VISIBLE);


        //高级设置
        advancedSetting = (LinearLayout) rootView.findViewById(R.id.drawer_advanced_setting);
        advancedSetting.setOnClickListener(this);
        //扫一扫
        saoyisao = (LinearLayout) rootView.findViewById(R.id.ll_saoyisao);
        saoyisao.setOnClickListener(this);
        //清除缓存
        cleanSession = (LinearLayout) rootView.findViewById(R.id.drawer_clean_session);
        cleanSession.setOnClickListener(this);
        cacheSize = (TextView) rootView.findViewById(R.id.cachesize);

        //检测新版本
        rootView.findViewById(R.id.ll_check_update).setOnClickListener(this);
        //关于我们
        LinearLayout setting_about = (LinearLayout) rootView.findViewById(R.id.setting_about);
        setting_about.setOnClickListener(this);
        //修改密码
        llChangepwd = (LinearLayout) rootView.findViewById(R.id.ll_changepwd);
        llChangepwd.setOnClickListener(this);
        if ("1".equals(EnvironmentVariable.getProperty("leftSlideShowChangePwd", "0"))) {
            llChangepwd.setVisibility(View.VISIBLE);
        }
        //设置
        llSetting = (LinearLayout) rootView.findViewById(R.id.ll_setting);
        if (EnvSupportManager.showLeftSetting()) {
            llSetting.setVisibility(View.VISIBLE);
            llSetting.setOnClickListener(this);
        }
        //换肤
        llSwitchChangeSkin = (LinearLayout) rootView.findViewById(R.id.ll_changeSkin);
        switchChangeSkin = (SwitchCompat) rootView.findViewById(R.id.switch_change_skin);
        tvSwitchSkin = (TextView) rootView.findViewById(R.id.tv_switch_skin);

        if (EnvSupportManager.isSupportSkin()) {
            //显示当前主题名称
            llSwitchChangeSkin.setVisibility(View.VISIBLE);
            switchChangeSkin.setOnClickListener(this);
            MyThemeBean bean = ThemeManager.getInstance(getActivity().getApplication()).getCurrentSkin();
            String skinTitle = bean.getType() == MyThemeBean.TYPE_IN_DEFAULT ?
                    ResStringUtil.getString(R.string.skin_mode_night) :
                    ResStringUtil.getString(R.string.skin_mode_daylight);
            tvSwitchSkin.setText(skinTitle);
            switchChangeSkin.setChecked(bean.getType() != MyThemeBean.TYPE_IN_DEFAULT);
        }
//        //多语言
//        ll_multi_language = (LinearLayout) rootView.findViewById(R.id.ll_multi_language);
//        if (EnvSupportManager.isSupportMultiLanguage()) {
//            ll_multi_language.setVisibility(View.VISIBLE);
//        }
//        ll_multi_language.setOnClickListener(this);
//        //换肤
//        llChangeSkin = (LinearLayout) rootView.findViewById(R.id.ll_change_skin);
//        if (EnvSupportManager.isSupportSkin()) {
//            llChangeSkin.setVisibility(View.VISIBLE);
//            llChangeSkin.setOnClickListener(this);
//        }
        //测试
        LinearLayout setting_test = (LinearLayout) rootView.findViewById(R.id.setting_test);
        setting_test.setOnClickListener(this);

        //退出登录
        Button exitBtn = (Button) rootView.findViewById(R.id.settings_exit);
        exitBtn.setOnClickListener(this);
        storageUtil = new StorageUtil(getActivity().getApplicationContext(), "storage");
    }

    /**
     * 铃声，振动设置，免打扰设置
     */
    private void initRingVibrator() {
        //铃声
        ringSwitch = (SwitchCompat) rootView.findViewById(R.id.switch_ring);
        ringSwitch.setChecked(RingVibratorUtils.isRinging());
        ringSwitch.setOnClickListener(this);
        //震动
        vibratorSwitch = (SwitchCompat) rootView.findViewById(R.id.switch_vibrate);
        vibratorSwitch.setChecked(RingVibratorUtils.isVibrate());
        vibratorSwitch.setOnClickListener(this);
        //免打扰
        noBrotherSwitch = (SwitchCompat) rootView.findViewById(R.id.switch_no_brother);
        noBrotherSwitch.setChecked(!(ringSwitch.isChecked() || vibratorSwitch.isChecked()));
        noBrotherSwitch.setOnClickListener(this);

        RadioGroup rg_touxiang = (RadioGroup) rootView.findViewById(R.id.rg_touxiang);
        RadioButton rb_round = (RadioButton) rootView.findViewById(R.id.rb_round);
        RadioButton rb_square = (RadioButton) rootView.findViewById(R.id.rb_square);
        String TX_type = EnvironmentVariable.getProperty("TX_type", "Square");
        if (TX_type.equals("Round")) {
            rb_round.setChecked(true);
        } else {
            rb_square.setChecked(true);
        }

        rg_touxiang.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_square) {
                    EnvironmentVariable.setProperty("TX_type", "Square");
                } else {
                    EnvironmentVariable.setProperty("TX_type", "Round");
                }
            }
        });
    }

    @Override
    public void onResume() {
        initUserInfo();
        super.onResume();
        //缓存
        File file = new File(AppConstant.APP_ROOT + "/meeting");
        if (!file.exists()) {
            file.mkdirs();

        }
        File file1 = new File(AppConstant.APP_ROOT + "/download");
        if (!file1.exists()) {
            file1.mkdirs();

        }
        //获取meeting文件夹大小 单位MB
        cacheFileSize1 = FileSizeUtil.getFileOrFilesSize(AppConstant.APP_ROOT + "/meeting", 3);
        cacheFileSize2 = FileSizeUtil.getFileOrFilesSize(AppConstant.APP_ROOT + "/download", 3);
        DecimalFormat df = new DecimalFormat("#######.##");
        String size1 = df.format(cacheFileSize1 + cacheFileSize2);
        cacheSize.setText(size1 + "MB");
    }

    /**
     * 初始化用户信息
     */
    private void initUserInfo() {
        user = WeChatDBManager.getInstance().
                getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID, "0")));
        avatar = user.getAvatar();
        tv_name.setText(user.getNickName());
//        fxid = user.getName();//帐号
        fxid = user.getId() + "";//帐号

        if ("1".equals(EnvironmentVariable.getProperty("showLoginID", "0"))) {
            //显示登陆账号  帐号：xxx
            fxid = user.getName();
            tv_fxid.setText(getResources().getText(R.string.chat_number) + ":" + fxid);
        } else {
            //显示联信消息帐号  ID：xxx
            if (fxid != null && !fxid.equals("")) {
                tv_fxid.setText(getResources().getText(R.string.im_chat_number) + ":" + fxid);
            } else {
                tv_fxid.setText(getResources().getText(R.string.im_chat_number) + ":" + getResources().getString(R.string.left_fragment_id_unsetting));
            }
        }


        if (user != null) {
            tv_name.setText(user.getNickName());
        }
        //imageLoader.displayImage( URLModifyDynamic.getInstance().replace(avatar),iv_avatar, options);
        lxGlideImageLoader.showUserAvatar(getActivity(), iv_avatar, avatar);
        initRoleImage();

        //性别
        sex = user.getSex();
        if (sex.equals("M")) {
            user_sex.setImageDrawable(JfResourceUtil.getSkinDrawable(R.drawable.chat_image_addfriend_sex_male));
        } else {
            user_sex.setImageDrawable(JfResourceUtil.getSkinDrawable(R.drawable.chat_image_addfriend_sex_female));
        }
        //个性签名
        TextView signatureTextView = (TextView) rootView.findViewById(R.id.drawer_signature);
        signatureTextView.setText(user.getSigNature());
    }

    /**
     * 初始化角色头像
     */
    private void initRoleImage() {
        //角色
        String key_tangzu_jsrq = EnvironmentVariable.getProperty("KEY_TANGZU_JSRQ");
        if (null != key_tangzu_jsrq && !"".equals(key_tangzu_jsrq) && !"null".equals(key_tangzu_jsrq) && !"undefined".equals(key_tangzu_jsrq)) {
            user_role.setVisibility(View.VISIBLE);
            switch (key_tangzu_jsrq) {
                case "2":
                    //医生
                    user_role.setImageDrawable(getResources().getDrawable(R.drawable.chat_left_jsrq_ys));
                    break;
                case "3":
                    //患者
                    user_role.setImageDrawable(getResources().getDrawable(R.drawable.chat_left_jsrq_hz));
                    break;
                case "4":
                    //亲友
                    user_role.setImageDrawable(getResources().getDrawable(R.drawable.chat_left_jsrq_qy));
                    break;
//                case "5":
//                    //护士
//                    user_role.setImageDrawable(getResources().getDrawable(com.efounder.chat.R.drawable.chat_left_jsrq_));
//                      break;
                case "7":
                    user_role.setImageDrawable(getResources().getDrawable(R.drawable.chat_left_jsrq_cjys));
                    break;
                case "8":
                    user_role.setImageDrawable(getResources().getDrawable(R.drawable.chat_left_jsrq_cs));
                    break;
                case "9":
                    user_role.setImageDrawable(getResources().getDrawable(R.drawable.chat_left_jsrq_yszl));
                    break;
                case "11":
                    user_role.setImageDrawable(getResources().getDrawable(R.drawable.chat_left_jsrq_gly));
                    break;

            }
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.setting_about) {
            Intent setIntent = new Intent(getActivity(), AboutActivityNew.class);
            startActivity(setIntent);

//            if (TbsVideo.canUseTbsPlayer(getActivity())){
//                TbsVideo.openVideo(getActivity(),Environment.getExternalStorageDirectory().toString()
//                +"/DCIM/Video/V80122-171341.mp4");
            // }

        } else if (id == R.id.settings_exit) {
            new CommonSettingManager(getActivity()).showExitLoginDialog();
        }
        //处理switch-------------begin
        else if (id == R.id.switch_ring) {
//          FIXME 换肤测试
//            SkinCompatManager.getInstance().loadSkin("mobile.skin", null, SkinCompatManager.SKIN_LOADER_STRATEGY_ASSETS);
            RingVibratorUtils.turnOnRing(ringSwitch.isChecked());
            noBrotherSwitch.setChecked(!(ringSwitch.isChecked() || vibratorSwitch.isChecked()));
        } else if (id == R.id.switch_vibrate) {
//          FIXME 换肤测试
//            SkinCompatManager.getInstance().restoreDefaultTheme();
            RingVibratorUtils.turnOnVibrator(vibratorSwitch.isChecked());
            noBrotherSwitch.setChecked(!(ringSwitch.isChecked() || vibratorSwitch.isChecked()));
        } else if (id == R.id.switch_no_brother) {
            //1.改变铃声状态
            ringSwitch.setChecked(!noBrotherSwitch.isChecked());
            RingVibratorUtils.turnOnRing(ringSwitch.isChecked());
            //2.改变震动状态
            vibratorSwitch.setChecked(!noBrotherSwitch.isChecked());
            RingVibratorUtils.turnOnVibrator(vibratorSwitch.isChecked());

        } else if (id == R.id.ll_saoyisao) {
            Intent saoyisaoIntent = new Intent(getActivity(), MipcaActivityCapture.class);
            startActivity(saoyisaoIntent);
        }
        //处理switch-------------end
        else if (id == R.id.drawer_advanced_setting) {
            Intent setIntent = new Intent(getActivity(), SettingActivity.class);
            startActivity(setIntent);
        } else if (id == R.id.drawer_clean_session) {
            if (cacheSize.getText().toString().equals("0MB")) {
                ToastUtil.showToast(getActivity(), getResources().getString(R.string.left_fragment_tip_nocache));
                return;
            }
            AlertDialog dialog = new AlertDialog.Builder(getActivity()).setNegativeButton(R.string.common_text_cancel, null).setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    FileDeleteUtil.DeleteFolder(AppConstant.APP_ROOT + "/meeting");
                    FileDeleteUtil.DeleteFolder(AppConstant.APP_ROOT + "/download");
                    CommonThreadPoolUtils.execute(new Runnable() {
                        @Override
                        public void run() {
                            Glide.get(getActivity()).clearDiskCache();
                        }
                    });
                    ToastUtil.showToast(AppContext.getInstance(), getResources().getString(R.string.left_fragment_tip_clear_cache_success));
                    cacheSize.setText("0MB");
                }
            }).setTitle(R.string.common_text_hint).setMessage(getResources().getString(R.string.left_fragment_tip_clear_cache)).show();

        } else if (id == R.id.ll_check_update) {
            if (EnvSupportManager.isSupportGooglePlayUpgrade()) {
                //google 商店版本
                new CommonSettingManager(getActivity()).checkGoogleStoreUpdate();
            } else {
                //应用内升级
                innerUpdate();
            }

        } else if (id == R.id.setting_test) {
            Intent intent = new Intent(getContext(), TestActivity.class);
            startActivity(intent);
        } else if (id == R.id.user_qr_code) {
            User user = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));

            Intent intent = new Intent(getContext(), CreateUserQRCode.class);

            Bundle bundle = new Bundle();
            bundle.putString("type", "addFriend");
            bundle.putString("id", EnvironmentVariable.getProperty(CHAT_USER_ID));
            bundle.putString("avatar", user.getAvatar());
            bundle.putString("nickname", user.getNickName());
            bundle.putString("name", user.getName());
            bundle.putString("sex", user.getSex());

            intent.putExtras(bundle);
            startActivity(intent);
        } else if (id == R.id.ll_changepwd) {
            //修改密码的菜单目前是给星际通讯使用的
            ReflectUtils reflectUtils = ReflectUtils.reflect("com.pansoft.openplanet.activity.ChangePasswordActivity");
            reflectUtils.method("start", getActivity());
        } else if (id == R.id.ll_multi_language) {
            //多语言
            MultiLanguageActivity.start(getActivity());
        } else if (id == R.id.ll_change_skin) {
            //切换主题
            ThemePreferenceActivity.start(getActivity());
        } else if (id == R.id.ll_setting) {
            //设置
            LxSettingActivity.start(getActivity());
        } else if (id == R.id.switch_change_skin) {
            //换肤
            changeSkin();
        }
    }

    /**
     * 更换皮肤，暂时只有日间和夜间区别
     * 也就是默认Default和其他的区别
     */
    private void changeSkin() {
        final ThemeManager themeManager = ThemeManager.getInstance(getActivity().getApplication());
        List<MyThemeBean> myThemeBeans = themeManager.getThemeList();
        if (myThemeBeans.size()<=1){
            //未配置相应皮肤包信息
            return;
        }
        changeTheme = myThemeBeans.get(0);
        if (themeManager.getCurrentSkin().getType() == changeTheme.getType()) {
            changeTheme = myThemeBeans.get(1);
        }
        ThemeManager.getInstance(getActivity().getApplication()).changeSkin(changeTheme, new SkinCompatManager.SkinLoaderListener() {
            @Override
            public void onStart() {
                LoadingDataUtilBlack.show(getActivity(), ResStringUtil.getString(R.string.common_text_please_wait));
            }

            @Override
            public void onSuccess() {
                //切换成功后记得保存一下
                themeManager.setCurrentSkin(changeTheme);
                MyThemeBean bean = ThemeManager.getInstance(getActivity().getApplication()).getCurrentSkin();
                String skinTitle = bean.getType() == MyThemeBean.TYPE_IN_DEFAULT ?
                        ResStringUtil.getString(R.string.skin_mode_night) :
                        ResStringUtil.getString(R.string.skin_mode_daylight);
                tvSwitchSkin.setText(skinTitle);
                switchChangeSkin.setChecked(bean.getType() != MyThemeBean.TYPE_IN_DEFAULT);
                //跳转首页
                try {
                    String className = getResources().getString(R.string.from_group_backto_first);
                    BlankActivity.start(getActivity(), className);
                    LoadingDataUtilBlack.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(String errMsg) {
                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToast(getActivity().getApplicationContext(), R.string.common_text_failed_please_retry);
            }
        });
    }

    LoginManager loginAction = new LoginManager(false);
    private Handler mHandler = new Handler();

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.e("==", TAG + "======setUserVisibleHint:isVisibleToUser:" + isVisibleToUser);
        if (isVisibleToUser) {
            initUserInfo();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LogoutEvent event) {
        LogOutUtil.notifyOffline(event);
    }

    //设备管理停用后下线处理。暂时注释掉
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(DisableEvent event) {
//        logout();
//    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    /**
     * 应用内升级
     */
    private void innerUpdate() {
        //loginAction.loginBegin(getContext(), EnvironmentVariable.getUserName(), EnvironmentVariable.getPassword(), true);
        String loginType = EnvironmentVariable.getProperty("LoginType");
        if (null != loginType && loginType.equals("0")) {
            //0表示restfu接口
//            LoginByRestFul loginByRestFul = new LoginByRestFul(2);
//            loginByRestFul.loginBegin(getContext(), EnvironmentVariable.getUserName(), EnvironmentVariable.getPassword());

            LoginCheckManager loginCheckManager = new LoginCheckManager(getActivity());
            loginCheckManager.checkVersionAfterLogin(LoginCheckManager.TYPE_CHECK_VERSION);

//            LoginByRestFulManager loginByRestFulManager = new LoginByRestFulManager(2);
//            loginByRestFulManager.loginBegin(getContext(), EnvironmentVariable.getUserName(), EnvironmentVariable.getPassword());

        } else {
            loginAction.loginBegin(getContext(), EnvironmentVariable.getUserName(), EnvironmentVariable.getPassword(), true);
        }
    }
}
